package com.ozo.cloud.gen.util.translate;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 网易有道智云翻译服务api调用工具类
 * api接口: https://openapi.youdao.com/api
 */
public class YoudaoTranslateUtil {

    private static final String APP_KEY = "2f418bc924b27c3a";     // 您的应用ID
    private static final String APP_SECRET = "cyb1h3dSOpaP31wM6zwAdxqRFyfzhYlp";  // 您的应用密钥
    private static final String API = "https://openapi.youdao.com/api";  // 您的应用密钥

    /**
     * 翻译成英文
     *
     * @param word
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String transEn(String word) throws NoSuchAlgorithmException {
        return trans("en", word);
    }

    /**
     * 翻译
     *
     * @param to
     * @param word
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String trans(String to, String word) throws NoSuchAlgorithmException {
        // 添加请求参数
        Map<String, String[]> params = createRequestParams(to, word);
        // 添加鉴权相关参数
        AuthV3Util.addAuthParams(APP_KEY, APP_SECRET, params);
        // 请求api服务
        byte[] result = HttpUtil.doPost(API, null, params, "application/json");
        if (result == null) {
            return null;
        }
        String result1 = new String(result, StandardCharsets.UTF_8);
        JSONObject jsonObject = JSONUtil.parseObj(result1);
        JSONArray translation = jsonObject.getJSONArray("translation");
        if (translation == null) {
            return null;
        }
        return translation.get(0).toString();
    }

    /**
     * 添加请求参数
     *
     * @param to
     * @param word
     * @return
     */
    private static Map<String, String[]> createRequestParams(String to, String word) {
        String from = "auto";
        return new HashMap<>() {{
            put("q", new String[]{word});
            put("from", new String[]{from});
            put("to", new String[]{to});
            put("vocabId", new String[]{});
        }};
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        System.out.println(transEn("小伙子有钱途"));
    }

}
